package com.us.usws.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.iwsh.core.db.DBExecutor;
import net.iwsh.core.db.ext.DialectSyntaxParser;
import net.iwsh.core.db.ext.SQLWithParams;

import com.us.usws.support.uitls.DataPageUtil;
import com.us.usws.support.uitls.FilterDto;
import com.us.usws.support.uitls.Order;
import com.us.usws.support.uitls.SQLHelpUtil;

public class BasePageSearchDAO<T> {
	/**
	 * DBExeutor
	 */
	protected DBExecutor dbe = new DBExecutor();
	
	protected SQLWithParams initSQLWithParams(DataPageUtil<T> dataPageUtil, List<Object> filedValues, String countSql, String sql) {
		if (filedValues == null) {
			filedValues = new ArrayList<Object>();
		}
		SQLWithParams swp = null;
		if (dataPageUtil != null) {
			Map<FilterDto, Object> filter = dataPageUtil.getFilter();
			if (filter != null) {
				String filterSql = SQLHelpUtil.createSQL(filter);
				countSql += " and " + filterSql;
				sql += " and " + filterSql;
				filedValues.addAll(SQLHelpUtil.getFiledValues());
			}
			Order o = dataPageUtil.getOrder();
			String orderType = "";
			if(o != null) {
				orderType = " order by "+ o.getFiledName() + (o.isDesc() ? " desc" : "");
			}
			sql += orderType;
			if (filedValues != null && filedValues.size() > 0) {
				dataPageUtil.setRowCount(dbe.getCount(countSql, filedValues.toArray()));
				swp = DialectSyntaxParser.getParser().getPaginationSQLWithParams(sql, filedValues.toArray(), dataPageUtil.getStart(),
						dataPageUtil.getPageSize());
			} else {
				dataPageUtil.setRowCount(dbe.getCount(countSql));
				swp = DialectSyntaxParser.getParser().getPaginationSQLWithParams(sql, null, dataPageUtil.getStart(),
						dataPageUtil.getPageSize());
			}
		}
		return swp;
	}
}
